package de.dubiel.plung.client.pages.account;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;

import de.dubiel.plung.client.events.UserDataSavedEvent;
import de.dubiel.plung.client.gin.ClientGinjector;
import de.dubiel.plung.shared.dao.User;

public class AccountViewImpl extends Composite implements AccountView {
    private static ActionUiBinder uiBinder = GWT.create(ActionUiBinder.class);

    interface ActionUiBinder extends UiBinder<Widget, AccountViewImpl> {
    }

    private ClientGinjector clientFactory;

    @UiField
    TextBox localPaddleColor;
    @UiField
    TextBox remotePaddleColor;
    @UiField
    TextBox ballColor;
    @UiField
    TextBox middleLineColor;
    @UiField
    TextBox fieldColor;

    @Inject
    public AccountViewImpl(ClientGinjector clientFactory) {
        initWidget(uiBinder.createAndBindUi(this));
        this.clientFactory = clientFactory;
    }

    @Override
    public void init() {
        readData(null);
    }

    @UiHandler("reset")
    protected void readData(ClickEvent event) {
        User user = this.clientFactory.getUserProvider().get();
        localPaddleColor.setValue(user.getLocalPaddleColor());
        remotePaddleColor.setValue(user.getRemotePaddleColor());
        ballColor.setValue(user.getBallColor());
        middleLineColor.setValue(user.getMiddleLineColor());
        fieldColor.setValue(user.getFieldColor());
    }

    @UiHandler("save")
    protected void saveData(ClickEvent event) {
        final User user = this.clientFactory.getUserProvider().get();
        user.setLocalPaddleColor(localPaddleColor.getValue());
        user.setRemotePaddleColor(remotePaddleColor.getValue());
        user.setBallColor(ballColor.getValue());
        user.setMiddleLineColor(middleLineColor.getValue());
        user.setFieldColor(fieldColor.getValue());
        clientFactory.getUserService().updateUser(user, new AsyncCallback<Void>() {
            @Override
            public void onSuccess(Void result) {
                AccountViewImpl.this.clientFactory.getEventBus().fireEvent(new UserDataSavedEvent());
            }

            @Override
            public void onFailure(Throwable caught) {
            }
        });
    }
}